import express, { Request, Response } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { query } from '../database';
import { authenticateToken } from '../middleware/auth';
import { body, validationResult } from 'express-validator';

const router = express.Router();

// 获取所有库存
router.get('/', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { page = 1, limit = 10, status, search } = req.query;
    
    // 确保分页参数是有效的数字
    const pageNum = Math.max(1, parseInt(page as string) || 1);
    const limitNum = Math.max(1, parseInt(limit as string) || 10);
    const offset = (pageNum - 1) * limitNum;
    
    let whereClause = '1=1';
    const params: any[] = [];

    if (status && status !== 'all') {
      whereClause += ' AND ir.type = ?';
      params.push(status);
    }

    if (search) {
      whereClause += ' AND (a.name LIKE ? OR ir.reason LIKE ?)';
      const searchTerm = `%${search}%`;
      params.push(searchTerm, searchTerm);
    }

    // 获取库存列表 - 使用字符串拼接LIMIT和OFFSET避免参数绑定问题
    console.log('Inventory query params:', params, 'limitNum:', limitNum, 'offset:', offset);
    console.log('Inventory WHERE clause:', whereClause);
    
    const inventory = await query(`
      SELECT ir.id, ir.asset_id as assetId, a.name as assetName,
             ir.quantity, ir.type, ir.reason,
             ir.operator_id as operatorId, ir.created_at as createdAt
      FROM inventory_records ir
      JOIN assets a ON ir.asset_id = a.id
      WHERE ${whereClause}
      ORDER BY ir.created_at DESC
      LIMIT ${limitNum} OFFSET ${offset}
    `, params);

    res.json({
      success: true,
      data: inventory
    });

  } catch (error) {
    console.error('获取库存列表失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 获取单个库存记录
router.get('/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    const inventory = await query(`
      SELECT ir.id, ir.asset_id as assetId, a.name as assetName,
             ir.quantity, ir.type, ir.reason,
             ir.operator_id as operatorId, ir.created_at as createdAt
      FROM inventory_records ir
      JOIN assets a ON ir.asset_id = a.id
      WHERE ir.id = ?
    `, [id]);

    if ((inventory as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '库存记录不存在' 
      });
    }

    res.json({
      success: true,
      data: (inventory as any[])[0]
    });

  } catch (error) {
    console.error('获取库存详情失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 创建库存记录
router.post('/', authenticateToken, [
  body('assetId').notEmpty().withMessage('资产ID不能为空'),
  body('quantity').isInt({ min: 1 }).withMessage('数量必须是正整数'),
  body('type').isIn(['盘入', '盘出']).withMessage('类型必须是盘入或盘出')
], async (req: Request, res: Response) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { assetId, quantity, type, reason } = req.body;
    const userId = (req as any).user.userId;
    const recordId = uuidv4();

    // 检查资产是否存在
    const assets = await query('SELECT id FROM assets WHERE id = ?', [assetId]);
    if ((assets as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '资产不存在' 
      });
    }

    await query(`
      INSERT INTO inventory_records (
        id, asset_id, type, quantity, reason, operator_id
      ) VALUES (?, ?, ?, ?, ?, ?)
    `, [recordId, assetId, type, quantity, reason || '', userId]);

    res.status(201).json({
      success: true,
      message: '库存记录创建成功',
      data: { id: recordId }
    });

  } catch (error) {
    console.error('创建库存记录失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 更新库存记录
router.put('/:id', authenticateToken, [
  body('quantity').optional().isInt({ min: 0 }).withMessage('数量必须是非负整数'),
  body('location').optional().notEmpty().withMessage('位置不能为空')
], async (req: Request, res: Response) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { id } = req.params;
    const { quantity, location, notes } = req.body;

    // 检查库存记录是否存在
    const records = await query('SELECT id FROM inventory_records WHERE id = ?', [id]);
    if ((records as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '库存记录不存在' 
      });
    }

    // 根据数量确定状态
    let status = 'normal';
    if (quantity !== undefined) {
      if (quantity === 0) {
        status = 'out_of_stock';
      } else if (quantity < 10) {
        status = 'low';
      }
    }

    // 字段映射：前端字段名 -> 数据库字段名
    const fieldMapping: { [key: string]: string } = {
      quantity: 'quantity',
      location: 'location', 
      notes: 'notes',
      status: 'status'
    };

    const updateFields: any = {};
    if (quantity !== undefined) {
      updateFields.quantity = quantity;
      updateFields.status = status;
    }
    if (location !== undefined) updateFields.location = location;
    if (notes !== undefined) updateFields.notes = notes;

    // 构建更新SQL
    const allowedFields = Object.keys(fieldMapping);
    const fieldsToUpdate = Object.keys(updateFields).filter(field => allowedFields.includes(field));
    
    if (fieldsToUpdate.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有有效的字段需要更新'
      });
    }

    const setClause = fieldsToUpdate.map(field => `${fieldMapping[field]} = ?`).join(', ');
    const values = fieldsToUpdate.map(field => updateFields[field]);

    await query(`
      UPDATE inventory_records 
      SET ${setClause}, updated_at = CURRENT_TIMESTAMP 
      WHERE id = ?
    `, [...values, id]);

    res.json({
      success: true,
      message: '库存记录更新成功'
    });

  } catch (error) {
    console.error('更新库存记录失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 库存盘点
router.post('/:id/check', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    // 检查库存记录是否存在
    const records = await query('SELECT id FROM inventory_records WHERE id = ?', [id]);
    if ((records as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '库存记录不存在' 
      });
    }

    // 更新最后盘点时间
    await query(`
      UPDATE inventory_records 
      SET last_checked = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP 
      WHERE id = ?
    `, [id]);

    res.json({
      success: true,
      message: '盘点完成'
    });

  } catch (error) {
    console.error('库存盘点失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 删除库存记录
router.delete('/:id', authenticateToken, async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    // 检查库存记录是否存在
    const records = await query('SELECT id FROM inventory_records WHERE id = ?', [id]);
    if ((records as any[]).length === 0) {
      return res.status(404).json({ 
        success: false, 
        message: '库存记录不存在' 
      });
    }

    // 删除库存记录
    await query('DELETE FROM inventory_records WHERE id = ?', [id]);

    res.json({
      success: true,
      message: '库存记录删除成功'
    });

  } catch (error) {
    console.error('删除库存记录失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

export default router;